package com.example.web03homework.Controller;

import com.example.web03homework.exception.ServiceException;
import com.example.web03homework.pojo.Category;
import com.example.web03homework.pojo.extend.CategoryExtend;
import com.example.web03homework.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/categories")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    // 查询所有分类
    @RequestMapping(value = "", method = RequestMethod.GET)
    public List<Category> getAllCategories() {
        return categoryService.getAllCategories();
    }
    
    // 查询所有一级分类信息（含所有二级分类）
    @RequestMapping(value = "/with-children", method = RequestMethod.GET)
    public List<CategoryExtend> getAllCategoriesWithChildren() {
        return categoryService.getAllCategoriesWithChildren();
    }
    
    // 根据ID查询分类
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Category getById(@PathVariable Integer id) {
        return categoryService.getById(id);
    }
    
    // 新增分类
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> addCategory(@RequestBody Category category) {
        categoryService.addCategory(category);
        return ResponseEntity.ok("分类添加成功");
    }
    
    // 修改分类
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseEntity<String> updateCategory(@RequestBody Category category) {
        categoryService.modifyCategory(category);
        return ResponseEntity.ok("分类修改成功");
    }
    
    // 删除分类
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteCategory(@PathVariable Integer id) {
        try {
            categoryService.removeById(id);
            return ResponseEntity.ok("分类删除成功");
        } catch (ServiceException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }
}
